import type {
    UserInfo,
    CourseMember,
    UserPreferences,
    CalendarPreferencesValue,
    DiscussionPreferencesValue,
    MessagePreferencesValue,
    ResourcePreferencesValue,
    UserCreateItem,
    ImportResult,
} from '@/types/user'
import http from './http'
import { apiMsgProp } from '@/utils/global'
import type { Pagination } from '@/types/global'

const UserService = {
    /**
     * @function create 创建用户
     * @param data 用户信息
     */
    create: async (data: UserCreateItem): Promise<UserInfo> => {
        const _data: any = { ...data }
        _data.interests = data.interests.join(',')
        const res = await http.post('/course/user/add', _data)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)

        return res.data.data
    },
    /**
     * @function delete 删除用户
     * @param ids 用户id组
     */
    delete: async (ids: number[]): Promise<void> => {
        const res = await http.delete('/course/user/batch', { data: { ids } })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function update 更新用户信息
     * @param data 用户信息
     */
    update: async (data: UserInfo): Promise<void> => {
        const res = await http.post('/course/user/update', { ...data, interests: data.interests.join('、') })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function getById 获取用户信息
     * @param id 用户 id
     * @returns UserInfo 用户信息
     */
    getById: async (id: number): Promise<UserInfo> => {
        const res = await http.get(`/course/user/${id}/info`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data
    },
    /**
     * @function getByToken 获取登录用户信息
     * @returns UserInfo 用户信息
     */
    getByToken: async (): Promise<UserInfo> => {
        const res = await http.get('/course/user/user-info')
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        res.data.data.interests = res.data.data.interests ? res.data.data.interests.split('、') : []
        return res.data.data
    },
    /**
     * @function list 获取用户列表(带分页)
     * @param searchForm 搜索条件
     * @returns UserInfo[] 用户列表
     */
    listWithPagination: async (searchForm: {
        key?: string
        role_id?: string
        first_initial?: string
        last_initial?: string
        page?: number
        limit?: number
    }): Promise<{ items: UserInfo[]; pagination?: Pagination }> => {
        let urlStr = '/course/user/list?'
        if (searchForm.key) urlStr += `&key=${searchForm.key}`
        if (searchForm.role_id) urlStr += `&role_id=${searchForm.role_id}`
        if (searchForm.first_initial && searchForm.first_initial !== 'all') urlStr += `&first_initial=${searchForm.first_initial}`
        if (searchForm.last_initial && searchForm.last_initial !== 'all') urlStr += `&last_initial=${searchForm.last_initial}`
        if (searchForm.page) urlStr += `&page=${searchForm.page}`
        if (searchForm.limit) urlStr += `&limit=${searchForm.limit}`
        const res = await http.get(urlStr)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }

        const data: { items: UserInfo[]; pagination?: Pagination } = {
            items: res.data.data.items,
        }
        if (searchForm.page) {
            data.pagination = {
                total: res.data.data.total,
                page: res.data.data.page,
                limit: res.data.data.limit,
            }
        }
        return data
    },
    /**
     * @function list 获取用户列表(不带分页)
     * @param role_id 角色id
     * @param key 关键字
     * @returns UserInfo[] 用户列表
     */
    list: async (role_id: number, key?: string): Promise<UserInfo[]> => {
        let urlStr = `/course/user/list?role_id=${role_id}`
        if (key) urlStr += `&key=${key}`
        const res = await http.get(urlStr)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data.items
    },
    /**
     * @function listToCourse 获取课程成员列表
     * @param courseId 课程id
     * @param searchForm 搜索条件
     * @returns CourseMember[] 课程成员列表
     */
    listToCourse: async (courseId: number, searchForm: { keyword?: string; role_id?: string; first_initial?: string; last_initial?: string; page?:number; limit?:number }): Promise<CourseMember[]> => {
        let apiUrl = `/course/user/course-members?course_id=${courseId}&page=${searchForm.page}&limit=${searchForm.limit}`
        if (searchForm.keyword) apiUrl += `&keyword=${searchForm.keyword}`
        if (searchForm.role_id) apiUrl += `&role_id=${searchForm.role_id}`
        if (searchForm.first_initial && searchForm.first_initial !== 'all') apiUrl += `&first_initial=${searchForm.first_initial}`
        if (searchForm.last_initial && searchForm.last_initial !== 'all') apiUrl += `&last_initial=${searchForm.last_initial}`

        const res = await http.get(apiUrl)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        // return res.data.data.items
        return {
            dataList: res.data.data.items,
            pagination: {
                page: res.data.data.page,
                limit: res.data.data.limit,
                total: res.data.data.total,
            },
        }
    },
    /**
     * @function preference 获取用户偏好
     * @param userId 用户id
     * @returns UserPreferences 用户偏好
     */
    preference: async (userId: number): Promise<UserPreferences> => {
        const res = await http.get(`/course/user-preference/list?user_id=${userId}`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data
    },
    /**
     * @function preferenceByKey 获取用户某个偏好
     * @param userId 用户id
     * @param key 偏好key
     * @returns T 偏好值
     */
    preferenceByKey: async <T>(userId: number, key: string): Promise<T> => {
        const res = await http.get(`/course/user-preference/get?user_id=${userId}&key=${key}`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data
    },
    /**
     * @function preferenceUpdate 更新用户偏好
     * @param userId 用户id
     * @param key 偏好key
     * @param value 偏好值
     */
    preferenceUpdate: async (
        userId: number,
        key: string,
        value: CalendarPreferencesValue | DiscussionPreferencesValue | MessagePreferencesValue | ResourcePreferencesValue | string,
    ): Promise<void> => {
        const res = await http.post(`/course/user-preference/update`, { user_id: userId, key, value })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function import 批量导入用户
     * @param data 文件
     * @returns ImportResult 导入结果
     */
    import: async (data: FormData): Promise<ImportResult> => {
        const res = await http.post(`/course/user/addMulti`, data, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            timeout: undefined,
        })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)

        return res.data.data
    },
}

export default UserService
